package com.hand.wfive.fragment

import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.doris.media.picker.model.MediaModel
import com.doris.media.picker.model.MediaPickerParameter
import com.doris.media.picker.result.contract.MediaPickerContract
import com.hand.wfive.R
import com.hand.wfive.activity.edit.FileCenterActivity
import com.hand.wfive.activity.edit.FileEditActivity
import com.hand.wfive.activity.edit.FileSelectActivity
import com.hand.wfive.activity.picker.PickerFileActivity
import com.hand.wfive.base.BaseFragment
import com.hand.wfive.entity.FileEvent
import com.hand.wfive.entity.FileListModel
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.GridSpaceItemDecoration
import com.hand.wfive.entity.Params
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import com.rxjava.rxlife.RxLife
import kotlinx.android.synthetic.main.fragment_home.rl_sign
import kotlinx.android.synthetic.main.fragment_home.rl_stamp
import kotlinx.android.synthetic.main.fragment_home.select_recyclerview
import kotlinx.android.synthetic.main.fragment_home.topBar
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.backgroundColor
import org.jetbrains.anko.find
import org.jetbrains.anko.leftPadding
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asClass
import java.text.SimpleDateFormat

class HomeFragment : BaseFragment() {
    override fun getLayoutId() = R.layout.fragment_home
    private var mPage = 1
    lateinit var mAdapter: FileAdapter
    private var mIndex = 0
    private var mFileId = ""
    private var mFileSize = 0L
    private var mErrorCount = 0
    private var mSuccessCount = 0
    private lateinit var mPickerModel: ArrayList<MediaModel>
    private lateinit var mPickerImage: ActivityResultLauncher<MediaPickerParameter>

    override fun init() {
        registerEventBus()
//           mTurnH5Pay = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
//               if (it.resultCode == BaseActivity.RESULT_OK) {
//                   getOrderStatus()
//               }
//           }
    }

    override fun initKotlinWidget() {
        mPickerImage = registerForActivityResult(MediaPickerContract()) {
            if (it.isPicker) {
                mIndex = 0
                mFileId = ""
                mFileSize = 0L
                mErrorCount = 0
                mSuccessCount = 0
                mPickerModel = it.getData()
                showLoadingTipC("正在上传图片")
                uploadImage()
            }
        }
        rl_sign.singleClick {
            FileSelectActivity.show(mContext, 0)
        }
        rl_stamp.singleClick {
            FileSelectActivity.show(mContext, 1)
        }
        topBar.addLeftImageButton(R.mipmap.ic_home_title, R.id.top_bar_left_text)
        topBar.leftPadding = resources.getDimensionPixelSize(R.dimen.dp_15)
        topBar.backgroundColor = Color.TRANSPARENT
        var list = ArrayList<Item>()
        list.add(Item(R.mipmap.ic_file_item_image, "上传图片"))
        list.add(Item(R.mipmap.ic_file_item_word, "上传word"))
        list.add(Item(R.mipmap.ic_file_item_pdf, "上传PDF"))
        list.add(Item(R.mipmap.ic_file_item_words, "文件中心"))
        val layoutManager = GridLayoutManager(mContext, 4)
        select_recyclerview.layoutManager = layoutManager
        select_recyclerview.addItemDecoration(GridSpaceItemDecoration(5, 0, 3))
        var selectadapter = SelectAdapter()
        selectadapter.setOnItemClickListener { _, _, position ->
            when (position) {
                0 -> {
                    //图片
                    mPickerImage.launch(MediaPickerParameter().max(9))
                }

                1 -> {
                    //word
                    PickerFileActivity.show(mContext, Params.pickerWord)
                }

                2 -> {
                    //pdf
                    PickerFileActivity.show(mContext, Params.pickerPdf)
                }

                3 -> {
                    //管理
//                    FileEditActivity.show(mContext)
                    FileCenterActivity.show(mContext)
                }
            }

        }
        select_recyclerview.adapter = selectadapter
        selectadapter.setNewInstance(list)

//        mAdapter = FileAdapter()
//        file_recyclerview.layoutManager = LinearLayoutManager(mContext)
//        file_recyclerview.adapter = mAdapter
//        mAdapter.setEmptyView(getEmptyView())
//        mAdapter.setOnItemClickListener { _, _, position ->
//            val model = mAdapter.getItem(position)
//
//        }
//        mAdapter.loadMoreModule.isEnableLoadMore = true
//        mAdapter.loadMoreModule.setOnLoadMoreListener {
//            loadData()
//        }
//
//        loadData()
    }

    private fun uploadImage() {
        val filePath = mPickerModel[mIndex].path
        val objectKey = "${UserManager.getInstance().userId}/file/${System.currentTimeMillis()}_${
            filePath.substring(filePath.lastIndexOf("/") + 1)
                .replace(",", "")
        }"
        OssRequest.getInstance().uploadFile(objectKey, filePath, object : OssCallBack {
            override fun onSuccess() {
                if (mFileId.isEmpty()) mFileId = objectKey
                else mFileId += ",$objectKey"
                mFileSize += mPickerModel[mIndex].size
                mSuccessCount++
                mIndex++
                if (mPickerModel.size > mIndex) {
                    uploadImage()
                } else {
                    uploadOver()
                }
            }

            override fun onFailure(msg: String) {
                mErrorCount++
                mIndex++
                if (mPickerModel.size > mIndex) {
                    uploadImage()
                } else {
                    uploadOver()
                }
            }
        })
    }

    private fun uploadOver() {
        val model = FileModel()
        model.status = Params.fileStatusUnsign
        model.fileName = "上传图片${System.currentTimeMillis()}"
        model.type = Params.fileTypeImage
        model.size = mFileSize
        model.fileId = mFileId
        OssRequest.getInstance().addCloudFile(model, object : OssCallBack {
            override fun onSuccess() {
                if (mErrorCount == 0) showSuccessTip("上传完成")
                else showNormalTip("上传完成，${mSuccessCount}个上传成功，${mErrorCount}个上传失败")
                EventBus.getDefault().post(FileEvent(Params.fileTypeAll, Params.fileStatusUnsign))
            }

            override fun onFailure(msg: String) {
                showNormalTip(msg.ifEmpty { "上传图片失败" })
            }
        })
    }

    class Item {
        var res: Int? = null
        var title: String? = null

        constructor(res: Int?, title: String?) {
            this.res = res
            this.title = title
        }
    }

    class SelectAdapter :
        BaseQuickAdapter<Item, BaseViewHolder>(R.layout.item_home_select), LoadMoreModule {
        override fun convert(holder: BaseViewHolder, item: Item) {
            holder.setImageResource(R.id.item_im, item.res!!)
            holder.setText(R.id.item_title, item.title)
        }
    }

    class FileAdapter :
        BaseQuickAdapter<FileModel, BaseViewHolder>(R.layout.item_file), LoadMoreModule {
        override fun convert(holder: BaseViewHolder, item: FileModel) {
            val view = holder.getView<ImageView>(R.id.iv_logo)
            when (item.type) {
                Params.fileTypeWord -> Glide.with(view)
                    .load(OssRequest.getInstance().getFileUrl(item.coverFileId))
                    .placeholder(R.mipmap.ic_file_item_pdf).into(view)

                Params.fileTypePdf -> Glide.with(view)
                    .load(OssRequest.getInstance().getFileUrl(item.coverFileId))
                    .placeholder(R.mipmap.ic_file_item_pdf).into(view)

                else -> {
                    var fileIds = item.fileId
                    if (fileIds.contains(",")) {
                        val splits = fileIds.split(",")
                        fileIds = splits[0]
                    }
                    Glide.with(view).load(OssRequest.getInstance().getFileUrl(fileIds))
                        .placeholder(R.mipmap.ic_file_item_pdf).into(view)
                }

            }


            holder.setText(R.id.tv_name, item.fileName)
            holder.setText(
                R.id.tv_time,
                "${item.updateTime}"
            )
            //        holder.setText(R.id.tv_size, "文件大小：${FileUtils.convertFileSize(item.size)}")
            holder.setText(R.id.tv_status, if ("2" == item.status) "已签" else "待签")
            holder.setVisible(R.id.v_line, getItemPosition(item) != itemCount - 1)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun doFileEvent(event: FileEvent) {
        if (event.type == Params.fileTypeAll) {
            mPage = 1
            loadData()
        }
    }

    private fun loadData() {
        RxHttp.postForm(ApiConfig.getUserFileList)
            .add("appid", LoginConfig.AppId)
            .add("userId", UserManager.getInstance().userId)
            .add("pageSize", 20)
            .add("type", Params.fileTypeAll)
            .add("page", mPage)
            .asClass<FileListModel>()
            .to(RxLife.toMain(this))
            .subscribe({
                Log.e("loadData", it.toString())
                if (it.code == ApiConfig.SUCCESSCODE) {
                    if (mPage == 1) {
                        mAdapter.setNewInstance(it.data.records)
                    } else {
                        mAdapter.addData(it.data.records)
                    }
                    if (it.data.records.isEmpty()) {
                        mAdapter.loadMoreModule.loadMoreEnd()
                    } else {
                        mPage++
                        mAdapter.loadMoreModule.loadMoreComplete()
                    }
                } else resetPage()
            }, {
                resetPage()
            })
    }

    private fun resetPage() {
        mPage--
        if (mPage < 1) mPage = 1
        mAdapter.loadMoreModule.loadMoreComplete()
    }

//    private fun getEmptyView(): View {
//        val view = LayoutInflater.from(mContext)
//            .inflate(R.layout.item_file_empty, file_recyclerview, false)
//        view.find<TextView>(R.id.tv_tip).text = "暂无文件"
//        return view
//    }
}